package com.xyz.apis.modules.api.service.impl;


import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.Slave;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xyz.apis.modules.api.entity.DemoUser;
import com.xyz.apis.modules.api.entity.OrderUser;
import com.xyz.apis.modules.api.mapper.DemoUserMapper;
import com.xyz.apis.modules.api.mapper.DemoUserMybatisPlusTestMapper;
import com.xyz.apis.modules.api.mapper.OrderMapper;
import com.xyz.apis.modules.api.service.DemoUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;

@Service
public class DemoUserServiceImpl implements DemoUserService {

    @Resource
    private DemoUserMapper userMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private DemoUserMybatisPlusTestMapper demoUserMybatisPlusTestMapper;

    @Override
    public List<DemoUser> selectUsersFromMaster() {
        return userMapper.selectUsers();
    }


    @Override
    @DS("sharding")
    public List<DemoUser> selectUsersFromShardingSlave() {
        return userMapper.selectUsers();
    }

    @DS("sharding")
    //@Slave
    //@DS("slave")
    @Override
    @Transactional
    public void addUser(DemoUser user) {
        //userMapper.addUser(user.getName(), user.getAge());
        //userMapper.addUserOrder(100L,user.getName(), user.getAge());
        OrderUser orderUser = new OrderUser();
        orderUser.setName("test sharding");

        int userIdInt=new Random().nextInt(9000)+10000;
        orderUser.setUserId(Long.parseLong(String.valueOf(userIdInt)));
        orderMapper.addOrder(orderUser);
        //测试事务
        //int a = 1/0;
    }

    @DS("sharding")
    @Override
    public void deleteUserById(Long id) {
        userMapper.deleteUserById(id);
    }

    //@DS("master")
    //@DS("sharding")
    @Slave
    @Override
    public  IPage<DemoUser> testMyBatisPlusFun(){

        DemoUser demoUser = new DemoUser();
        demoUser.setAge(111);
        demoUser.setName("test");
        demoUserMybatisPlusTestMapper.insert(demoUser);
        //demoUserMybatisPlusTestMapper.updateById()

        List<DemoUser> demoUsersList = demoUserMybatisPlusTestMapper.selectList(null);
        demoUsersList.forEach(System.out::println);

        IPage<DemoUser> pages = new Page<>(1,10);
        IPage<DemoUser> demoUserIPage = demoUserMybatisPlusTestMapper.selectPage(pages,null);

        return demoUserIPage;
    }

    public static void main(String[] args) {
        int userIdInt=new Random().nextInt(9000)+10000;
        System.out.println(userIdInt);
    }
}
